package com.shujia.mllib

import org.apache.spark.ml.classification.LogisticRegressionModel
import org.apache.spark.ml.linalg
import org.apache.spark.ml.linalg.Vectors
import org.apache.spark.sql.{DataFrame, Row, SparkSession}

object Demo7UseImageModel {
  def main(args: Array[String]): Unit = {
    val spark: SparkSession = SparkSession
      .builder()
      .master("local[6]")
      .appName("image")
      .getOrCreate()
    import spark.implicits._
    import org.apache.spark.sql.functions._


    val imageData: DataFrame = spark.read
      .format("image")
      .load("data/image_test")


    val nameAndFeatures: DataFrame = imageData
      .select($"image.origin" as "origin", $"image.data" as "data")
      .map {
        case Row(origin: String, data: Array[Byte]) =>

          //将数据进行标准化，黑像素点使用0代替，白的像素点使用1代替
          val point: Array[Double] = data.map(i => {
            if (i.toInt >= 0) {
              0.0
            } else {
              1.0
            }
          })

          //将特征转换成向量
          val features: linalg.Vector = Vectors.dense(point)


          //获取图片名
          val name: String = origin.split("/").last

          (name, features)
      }
      .toDF("name", "features")


    /**
      * 加载图片模型
      *
      */

    val model: LogisticRegressionModel = LogisticRegressionModel.load("data/image_model")

    //使用模型判断图片中的数字
    val testDF: DataFrame = model.transform(nameAndFeatures)


    testDF.show(1000)
  }

}
